import type { Module } from 'vuex'
import type { TagsStateType } from './tags.typings'
import { isEqual } from 'lodash'
import { setStore, getStore } from '~/utils/store'
import defaultSettings from '~/defaultSettings'

// 默认初始化首页
const firstTag: TagsStateType['tag'] = {
  label: '首页',
  value: defaultSettings.defaultPage,
  params: {},
  query: '',
  close: false
}

const tags: Module<TagsStateType, TagsStateType> = {
  namespaced: true,
  state: {
    tagList: (getStore({ name: 'tagList' }) as TagsStateType['tagList']) || [firstTag],
    tag: (getStore({ name: 'tag' }) as TagsStateType['tag']) || {
      label: '', // 标题名称
      value: '', // 标题的路径
      params: {}, // 标题的路径参数
      query: '', // 标题的参数
      close: true // 是否可以关闭tag
    }
  },
  getters: {
    tagList: (state) => state.tagList,
    tag: (state) => state.tag
  },
  mutations: {
    CHANGE_TAG: (state, action: TagsStateType['tag']) => {
      if (isEqual(state.tag, action)) return
      state.tag = action
      setStore({ name: 'tag', content: action, type: 'session' })
    },
    ADD_TAG: (state, action: TagsStateType['tag']) => {
      if (state.tagList.find((item) => isEqual(item, action))) return
      state.tag = action
      state.tagList.push(action)
      setStore({ name: 'tag', content: action, type: 'session' })
      setStore({ name: 'tagList', content: state.tagList, type: 'session' })
    },
    DEL_TAG: (state, action: TagsStateType['tag']) => {
      state.tagList = state.tagList.filter((item) => !isEqual(item, action))
      state.tag = state.tagList[state.tagList.length - 1]
      setStore({ name: 'tag', content: state.tagList[state.tagList.length - 1], type: 'session' })
      setStore({ name: 'tagList', content: state.tagList, type: 'session' })
    },
    DEL_ALL_TAG: (state) => {
      state.tag = firstTag
      state.tagList = [firstTag]
      setStore({ name: 'tag', content: firstTag, type: 'session' })
      setStore({ name: 'tagList', content: state.tagList, type: 'session' })
    },
    DEL_OTHER_TAG: (state) => {
      state.tagList = state.tagList.filter(
        (item, index) => index === 0 || item.value === state.tag.value
      )
      setStore({ name: 'tagList', content: state.tagList, type: 'session' })
    }
  }
}
export default tags
